package com.frogs.ucenter.v1.service.impl.aop;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.frogs.framework.util.PageList;
import com.frogs.framework.util.StringUtil;
import com.frogs.framework.web.HttpRequestInfo;
import com.frogs.system.util.ApiUrlParamEnum;
import com.frogs.system.util.AttentionStateEnum;
import com.frogs.system.util.DataTypeInfoEnum;
import com.frogs.system.util.HonorRefEnum;
import com.frogs.system.util.HonorTypeEnum;
import com.frogs.system.util.OpenPlatformEnum;
import com.frogs.system.util.TaskActionListEmum;
import com.frogs.system.web.api.entity.FeedsRecordActiveMqEntity;
import com.frogs.system.web.api.request.Request;
import com.frogs.system.web.api.response.Response;
import com.frogs.system.web.api.response.Response.ApiResultEnum;
import com.frogs.ucenter.dao.UserAttentionInfoDao;
import com.frogs.ucenter.dao.WechatUserBaseInfoDao;
import com.frogs.ucenter.entity.WechatUserBaseInfo;
import com.frogs.ucenter.entity.ext.UserAttentionInfoExt;
import com.frogs.ucenter.util.record.FeedsRecordActiveMqSend;
import com.frogs.ucenter.util.task.TaskActionMqSend;
import com.frogs.ucenter.v1.request.UserAttentionAddRequest;
import com.frogs.ucenter.v1.request.UserPraiseInfoAddRequest;
import com.frogs.ucenter.v1.request.UserRemindedInfoAddRequest;
import com.frogs.ucenter.v1.service.UserHonorService;
import com.frogs.ucenter.v1.util.ApiConstants;
import com.sun.jersey.api.client.ClientResponse.Status;

@Aspect
@Service(ApiConstants.VERSION+"userHonorAopImpl")
public class UserHonorAopImpl extends BaseTaskAop {
	
	private static final Logger log = LoggerFactory.getLogger(UserHonorAopImpl.class);
	
	@Autowired
	private UserHonorService userHonorService;
	@Autowired
	private UserAttentionInfoDao userAttentionDao;
	@Autowired
	private FeedsRecordActiveMqSend feedsRecordActiveMqSend;
	@Autowired
	private WechatUserBaseInfoDao wechatUserBaseInfoDao;
	@Resource
	private TaskActionMqSend taskActionMqSend;
	
	/**
	 * 一键提醒测量场景
	 * @param jp 切入点
	 */
	@AfterReturning(pointcut="execution(* com.frogs.ucenter.v1.controller.UserRemindedInfoController.doRemind(..))",returning="result")
	public void doAfterReturning(JoinPoint jp, Response result)
	{
		try {
			Integer code = result.getCode();
			if(1 != code ){
				return;
			}
			UserRemindedInfoAddRequest addRequset  = new UserRemindedInfoAddRequest();
			addRequset.parse((HttpServletRequest) jp.getArgs()[0]);
			String detail = "";
			if(addRequset.getDataType()==DataTypeInfoEnum.BLOOD_PRESSURE.getId()){
				detail = HonorRefEnum.TI_XING_CL.getName();
			}else if(addRequset.getDataType()==DataTypeInfoEnum.BLOOD_GLUCOSE.getId()){
				detail = HonorRefEnum.TI_XING_CLXT.getName();
			}
			userHonorService.insertUserHonorScore(addRequset.getUserId(),
					HonorTypeEnum.XIAO_XIN.getId(), 10,
					detail,
					addRequset.getFollowedUserId(),
					addRequset.getOpenPlatformId(),true);
			
			
			Map<String, Object> params = new HashMap<String, Object>();
			String actionRecord = "realName提醒了nickName测量"+addRequset.getContent();
			params.clear();
			params.put("eqUserId", addRequset.getFollowedUserId());
			PageList<WechatUserBaseInfo> followUser = wechatUserBaseInfoDao.selectByMap(params, false);
			actionRecord = actionRecord.replace("nickName", followUser.get(0).getNickName());
			
			params.clear();
			params.put("eqWechatApplicationId", OpenPlatformEnum.WECHAT_HDC.getId());
			params.put("eqUserId", addRequset.getUserId());
			PageList<WechatUserBaseInfo> list = wechatUserBaseInfoDao.selectByMap(params , 1 , 1, false);
			
			insertUserFeedsRecord(addRequset.getUserId(),actionRecord,addRequset.getMessage(),list.get(0).getNickName());
			log.info("UserHonorAopImpl.insertUserHonorScore========");
		
		} catch (Exception e) {
			log.error("func[@After] jp[" + jp + "] result[" + result + "] error[" + e.getMessage() + "]", e);
		}
		
	}
	
	/**
	 * 关注家人场景
	 * @param jp 切入点
	 */
	@AfterReturning(pointcut="execution(* com.frogs.ucenter.v1.controller.UserAttentionController.attentionAdd(..)) || "
			+ "execution(* com.frogs.ucenter.v1.controller.UserAttentionController.attentionUpdate(..))",returning="result")
	public void doAttentionAdd(JoinPoint jp, Response result)
	{
		try {
			Integer code = result.getCode();
			if(1 != code ){
				return;
			}
			HttpServletRequest req  = (HttpServletRequest)jp.getArgs()[0];
			HttpRequestInfo requestInfo = new HttpRequestInfo(req);
			
			int openPlatformId = requestInfo.getIntParameter(ApiUrlParamEnum.openPlatformId.getParamName(), OpenPlatformEnum.WECHAT_HDC.getId());
			int followedUserId = requestInfo.getIntParameter(ApiUrlParamEnum.followedUserId.getParamName());
			int followUserId = requestInfo.getIntParameter(ApiUrlParamEnum.followUserId.getParamName());
			int status = requestInfo.getIntParameter(ApiUrlParamEnum.status.getParamName());
			
			if (status == AttentionStateEnum.ATTENTION_STATUS_AGREED.getId()) {
				Response response = userHonorService.insertUserHonorScore(followUserId,
						HonorTypeEnum.XIAO_XIN.getId(), 10,
						HonorRefEnum.GUAN_ZHU.getName(),
						followedUserId,
						openPlatformId,false);
				log.info("UserHonorAopImpl.doAttentionAdd========");
				if (response.getCode() == ApiResultEnum.SUCCESS.getId()) { //添加任务关注日志
					taskActionMqSend.send(TaskActionListEmum.ATTENTION.getId(), new BigDecimal("0.0"), "关注成功", followUserId, openPlatformId);
				}
			}
			
		} catch (Exception e) {
			log.error("func[@After] jp[" + jp + "] result[" + result + "] error[" + e.getMessage() + "]", e);
		}
		
	}
	
	/**
	 * 点赞场景
	 * @param jp 切入点
	 */
	@AfterReturning(pointcut="execution(* com.frogs.ucenter.v1.controller.UserPraiseInfoController.doPraise(..))",returning="result")
	public void doPraise(JoinPoint jp, Response result)
	{
		try {
			Integer code = result.getCode();
			if(1 != code ){
				return;
			}
			UserPraiseInfoAddRequest addRequset  = new UserPraiseInfoAddRequest();
			addRequset.parse((HttpServletRequest) jp.getArgs()[0]);
			userHonorService.insertUserHonorScore(addRequset.getUserId(),
					HonorTypeEnum.XIAO_XIN.getId(), 10,
					HonorRefEnum.DIAN_ZAN.getName(),
					addRequset.getFollowedUserId(),
					addRequset.getOpenPlatformId(),true);
			
			Map<String, Object> params = new HashMap<String, Object>();
			String actionRecord = "realName给nickName点了赞。";
			params.clear();
			params.put("eqUserId", addRequset.getFollowedUserId());
			PageList<WechatUserBaseInfo> followUser = wechatUserBaseInfoDao.selectByMap(params, false);
			actionRecord = actionRecord.replace("nickName", followUser.get(0).getNickName());
			
			params.clear();
			params.put("eqWechatApplicationId", OpenPlatformEnum.WECHAT_HDC.getId());
			params.put("eqUserId", addRequset.getUserId());
			PageList<WechatUserBaseInfo> list = wechatUserBaseInfoDao.selectByMap(params , 1 , 1, false);
			insertUserFeedsRecord(addRequset.getUserId(),actionRecord,addRequset.getMessage(),list.get(0).getNickName());
			log.info("UserHonorAopImpl.doPraise========");
		} catch (Exception e) {
			log.error("func[@After] jp[" + jp + "] result[" + result + "] error[" + e.getMessage() + "]", e);
		}
		
	}

	/**
	 * 记录用户行为
	 * @param userId
	 * @param actionRecord
	 */
	private void insertUserFeedsRecord(int userId,String actionRecord,String message,String ownName) {
		try {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("eqFollowedUserId", userId);
			params.put("eqStatus", AttentionStateEnum.ATTENTION_STATUS_AGREED.getId());
			params.put("eqOpenPlatformId", OpenPlatformEnum.WECHAT_HDC.getId());
			List<UserAttentionInfoExt> list = userAttentionDao.selectByMapForAttention(params,0,1000); 
			String copyActionRecord = actionRecord;
			
			FeedsRecordActiveMqEntity feedsRecordActiveMqEntity = new FeedsRecordActiveMqEntity();
			feedsRecordActiveMqEntity.setFollowedUserId(userId);
			feedsRecordActiveMqEntity.setMessage(message);      
			feedsRecordActiveMqEntity.setType(0); 
			
			
			for (UserAttentionInfoExt userAttentionInfoExt : list) {
				actionRecord = actionRecord.replace("realName", StringUtil.isEmpty(userAttentionInfoExt.getRealName())?ownName:userAttentionInfoExt.getRealName());
				FeedsRecordActiveMqEntity feedsRecordActiveMqEntityCopy = new FeedsRecordActiveMqEntity();
				BeanUtils.copyProperties(feedsRecordActiveMqEntityCopy,feedsRecordActiveMqEntity);  
				
				feedsRecordActiveMqEntityCopy.setFamilyId(userAttentionInfoExt.getFamilyId());
				feedsRecordActiveMqEntityCopy.setFollowUserId(userAttentionInfoExt.getFollowUserId());
				feedsRecordActiveMqEntityCopy.setActionRecord(actionRecord);
				log.info("发送到activeMq队列的数据："+JSON.toJSONString(feedsRecordActiveMqEntityCopy));  
				feedsRecordActiveMqSend.sendToQueue(feedsRecordActiveMqEntityCopy);
				actionRecord = copyActionRecord;
			}
			
		} catch (Exception e) {
			log.error("func[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						"动作发起用户id："+userId+"动作记录："+actionRecord, e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}
		
	}
}
